package com.fc.mall.portal.wechat;


import com.fc.mall.exception.ServiceException;
import com.fc.mall.portal.wechat.dto.WXPaymentResponse;
import com.fc.mall.portal.wechat.dto.WxConfig;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Sunny on 2019/4/25.
 */
public class WXPayUtil {
    private static Logger logger = LoggerFactory.getLogger(WXPayUtil.class);

    /**
     * 微信统一下单接口
     * @param orderNumber  订单号
     * @param total  金额
     * @param openId  微信用户openId
     * @param spbillCreateIp  当前IP地址
     * @return
     */
    public static WXPaymentResponse unifiedOrder(WxConfig wxConfig, String orderNumber, BigDecimal total, String openId, String spbillCreateIp) {
        //调用统一支付接口
        String nonceString = RandomStringUtils.randomAlphabetic(32);
        String body = "order:" + orderNumber;
        String totalFee = String.valueOf(total.multiply(new BigDecimal(100)).intValue());
        if(wxConfig.isDebug())
        {
            totalFee = "1";
        }
        String out_trade_no = orderNumber;

        SortedMap<Object,Object> parameters;
        if(wxConfig.isUseWsp())
        {
            parameters = getParametersForWsp(wxConfig, body, nonceString, openId, out_trade_no, spbillCreateIp, totalFee);
        }
        else
        {
            parameters = getNormalParameters(wxConfig, body, nonceString, openId, out_trade_no, spbillCreateIp, totalFee);
        }


        String requestBodyXMl = PaymentCommonUtil.getRequestXml(parameters);
        try {
            String wxResult = WechatCall.wxHttpRequest(wxConfig.getUnifiedOrderUrl(), requestBodyXMl);
            Map<String, Object> resultMap = PaymentCommonUtil.doXMLParse(wxResult);
            String success = "SUCCESS";
            if (success.equalsIgnoreCase((String)resultMap.get("return_code")) && success.equalsIgnoreCase((String)resultMap.get("result_code")))
            {
                //准备调微信支付的requestBody
                WXPaymentResponse unifiedorderResponse = new WXPaymentResponse();
                /**
                 * 正常支付 与 服务商支付 传 不同的APPID
                 */
                unifiedorderResponse.setAppId(wxConfig.isUseWsp() ? wxConfig.getSubAppId() : wxConfig.getAppId());
                unifiedorderResponse.setNonceStr((String)resultMap.get("nonce_str"));

                unifiedorderResponse.setTimestamp(String.valueOf(System.currentTimeMillis()));
                unifiedorderResponse.setPrepayId("prepay_id="+(String)resultMap.get("prepay_id"));

                String signTemplete = "appId=%s&nonceStr=%s&package=%s&signType=%s&timeStamp=%s";
                String sign = String.format(signTemplete, unifiedorderResponse.getAppId(), unifiedorderResponse.getNonceStr(), unifiedorderResponse.getPrepayId(), "MD5", unifiedorderResponse.getTimestamp())+"&key=" + wxConfig.getPayKey();
                unifiedorderResponse.setSign(DigestUtils.md5Hex(sign).toUpperCase());

                return unifiedorderResponse;
            }
            else
            {
                throw new ServiceException(wxResult);
            }
        }
        catch (Throwable e)
        {
            e.printStackTrace();
            throw new ServiceException("微信支付失败!");
        }
    }


    /**
     * 获取正常支付集合
     * @param wxConfig
     * @param body
     * @param nonceString
     * @param openId
     * @param out_trade_no
     * @param spbillCreateIp
     * @param totalFee
     * @return
     */
    private static SortedMap<Object,Object> getNormalParameters(WxConfig wxConfig,
                                                        String body,
                                                        String nonceString,
                                                        String openId,
                                                        String out_trade_no,
                                                        String spbillCreateIp,
                                                        String totalFee)
    {
        SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
        parameters.put("appid", wxConfig.getAppId());
        parameters.put("body", body);
        parameters.put("mch_id", wxConfig.getMchId());
        parameters.put("nonce_str", nonceString);
        parameters.put("notify_url", wxConfig.getNotifyUrl());
        parameters.put("openid", openId);
        parameters.put("out_trade_no", out_trade_no);
        parameters.put("spbill_create_ip", spbillCreateIp);
        parameters.put("total_fee",  totalFee);
        parameters.put("trade_type", wxConfig.getTradeType());
        parameters.put("sign", PaymentCommonUtil.createSign(wxConfig, nonceString, body, openId, out_trade_no,spbillCreateIp, totalFee));

        return parameters;
    }


    /**
     * 获取正服务商支付集合
     * @param wxConfig
     * @param body
     * @param nonceString
     * @param openId
     * @param out_trade_no
     * @param spbillCreateIp
     * @param totalFee
     * @return
     */
    private static SortedMap<Object,Object> getParametersForWsp(WxConfig wxConfig,
                                                          String body,
                                                          String nonceString,
                                                          String openId,
                                                          String out_trade_no,
                                                          String spbillCreateIp,
                                                          String totalFee)
    {
        SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
        parameters.put("appid", wxConfig.getAppId());
        parameters.put("body", body);
        parameters.put("mch_id", wxConfig.getMchId());
        parameters.put("nonce_str", nonceString);
        parameters.put("notify_url", wxConfig.getNotifyUrl());
        parameters.put("out_trade_no", out_trade_no);
        parameters.put("spbill_create_ip", spbillCreateIp);
        parameters.put("sub_appid", wxConfig.getSubAppId());
        parameters.put("sub_mch_id", wxConfig.getSubMchId());
        parameters.put("sub_openid", openId);
        parameters.put("total_fee",  totalFee);
        parameters.put("trade_type", wxConfig.getTradeType());
        parameters.put("sign", PaymentCommonUtil.createSignForWsp(wxConfig, nonceString, body, openId, out_trade_no,spbillCreateIp, totalFee));

        return parameters;
    }


    /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
     *
     * @param strxml
     * @return
     * @throws org.jdom2.JDOMException
     */
    public static Map<String, String> doXMLParse(String strxml) {
        if (null == strxml || "".equals(strxml)) {
            return null;
        }
        Map<String, String> m = new HashMap();
        InputStream in = String2Inputstream(strxml);
        try
        {
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(in);
            Element root = doc.getRootElement();
            List list = root.getChildren();
            Iterator it = list.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String k = e.getName();
                String v = "";
                List children = e.getChildren();
                if (children.isEmpty()) {
                    v = e.getTextNormalize();
                } else {
                    v = getChildrenText(children);
                }

                m.put(k, v);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                //关闭流
                in.close();
            }
            catch (Exception e1)
            {
            }
        }
        return m;
    }



    /**
     * 获取子结点的xml
     *
     * @param children
     * @return String
     */
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if (!children.isEmpty()) {
            Iterator it = children.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if (!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }

        return sb.toString();
    }

    public static InputStream String2Inputstream(String str) {
        return new ByteArrayInputStream(str.getBytes());
    }


    /**
     * 除去数组中的空值和签名参数
     *
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {
        Map<String, String> result = new HashMap<String, String>();
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
                    || key.equalsIgnoreCase("sign_type")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }


    /**
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     *
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        return prestr;
    }

    /**
     * 签名字符串
     *
     * @param text          需要签名的字符串
     * @param sign          签名结果
     * @param key           密钥
     * @param input_charset 编码格式
     * @return 签名结果
     */
    public static boolean verify(String text, String sign, String key, String input_charset) {
        text = text + key;
        String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
        if (mysign.equals(sign)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param content
     * @param charset
     * @return
     * @throws java.security.SignatureException
     * @throws UnsupportedEncodingException
     */
    public static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

}
